package com.party.jackclientandroid.ui_home.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.party.jackclientandroid.BaseFragment;
import com.party.jackclientandroid.Constant;
import com.party.jackclientandroid.MainActivity;
import com.party.jackclientandroid.R;
import com.party.jackclientandroid.adapter.MyCommonAdapter;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.HomeService;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.ShopItemMessage;
import com.party.jackclientandroid.controller.DialogController;
import com.party.jackclientandroid.controller.HomeFragmentController;
import com.party.jackclientandroid.controller.ShopItemController;
import com.party.jackclientandroid.loadviewhelper.load.LoadViewHelper;
import com.party.jackclientandroid.ui_home.activity.DiscountPayBillActivity;
import com.party.jackclientandroid.ui_home.activity.SearchActivity;
import com.party.jackclientandroid.ui_home.activity.ShopDetailActivity;
import com.party.jackclientandroid.ui_scan.ScanActivity;
import com.party.jackclientandroid.utils.ConstUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.scwang.smartrefresh.layout.util.DensityUtil;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.yinglan.alphatabs.AlphaTabsIndicator;
import com.zaaach.citypicker.model.HotCity;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 首页-首页
 */
public class HomeFragment extends BaseFragment {
    @BindView(R.id.ll_container)
    LinearLayout ll_container;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.position_tv)
    TextView positionTv;
    @BindView(R.id.scan_code_iv)
    ImageView scan_code_iv;

    HomeFragmentController controller;

    HomeService homeService;
    List<ShopItemMessage> recommendShopMessageList = new ArrayList<>();
    HeaderAndFooterWrapper mHeaderAndFooterWrapper;
    MyCommonAdapter<ShopItemMessage> commonAdapter;
    int page = 1;
    List<HotCity> hotCities;
    int headViewCount;

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        return view;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_home;
    }


    @Override
    protected void initData() {
        initHotCities();
        homeService = new HomeService(mActivity);
        helper = new LoadViewHelper(ll_container);
        helper.setListener(() -> {
            getNeedData();
        });

        controller = new HomeFragmentController(this, homeService);
        mRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        ShopItemController shopItemController = new ShopItemController(mActivity, mRecyclerView, mRefreshLayout);
        commonAdapter = shopItemController.initAdapter(recommendShopMessageList);
        mHeaderAndFooterWrapper = new HeaderAndFooterWrapper(commonAdapter);
        mHeaderAndFooterWrapper.addHeaderView(controller.getHeaderView(mRecyclerView));
        mRecyclerView.setAdapter(mHeaderAndFooterWrapper);
        headViewCount = mHeaderAndFooterWrapper.getHeadersCount();
        setNewLocationInfo(mApplication.getMap().getDistrict());
        getNeedData();


    }

    Bitmap bitmap;

    public Bitmap returnBitMap(final String url) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;

                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return bitmap;
    }


    @Override
    protected void initListener() {
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                handleItemClick(position);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return true;
            }
        });
        mRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getNeedData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                getNeedData();
            }
        });
    }

    /**
     * item点击事件
     *
     * @param position
     */

    private void handleItemClick(int position) {
        ShopItemMessage recommendShopMessage = recommendShopMessageList.get(position - headViewCount);
        mActivity.startActivity(ShopDetailActivity.class, "shopId", recommendShopMessage.getId() + "");
    }

    /**
     * 下拉获取数据
     */
    public void getNeedData() {
        helper.showLoading();
        addDisposableIoMain(homeService.getRecommendShopList(page, Constant.PAGE_SIZE), new DefaultConsumer<List<ShopItemMessage>>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<List<ShopItemMessage>> baseBean) {
                commonAdapter.clear(page);
                commonAdapter.addData(baseBean.getData());
                commonAdapter.finishLoading(page, Constant.PAGE_SIZE, baseBean.getData().size(), mRefreshLayout);
//                helper.check(baseBean.getData());
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //controller.releaseBanner();
    }

    /**
     * 界面不可见的时候停止Banner自动滚动
     *
     * @param isVisibleToUser
     * @param invokeInResumeOrPause
     */
    @Override
    public void onVisibleToUserChanged(boolean isVisibleToUser, boolean invokeInResumeOrPause) {
        if (isVisibleToUser) {
            controller.startAutoPlay();
        } else {
            controller.stopAutoPlay();
        }
    }

    /**
     * 点击扫一扫
     */
    @OnClick(R.id.scan_code_iv)
    public void clickScanCode() {
        Intent intent = new Intent(mActivity, ScanActivity.class);
        startActivityForResult(intent, ConstUtils.SCAN_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == ConstUtils.SCAN_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    if (result.contains("paiduikeji")) {
                        String shopCode = result.substring(result.indexOf("?") + 3, result.length());
                        getShopId(shopCode);
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    showToast("解析二维码失败");
                }
            }
        }
    }

    public void getShopId(String shopCode) {
        addDisposableIoMain(homeService.getShopIdByCode(shopCode), new DefaultConsumer<String>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<String> result) {
                mActivity.startActivity(DiscountPayBillActivity.class, "shopId", result.getData() + "");
                // mActivity.startActivity(ShopDetailActivity.class, "shopId", result.getData() + "");
            }

            @Override
            public void operateError(String message) {
                DialogController.showConfirmDialog(mActivity, "温馨提示", message);
            }
        });
    }

    /**
     * 点击搜索
     */
    @OnClick(R.id.search_ll)
    public void clickSearch() {
        Intent intent = new Intent(mActivity, SearchActivity.class);
        intent.putExtra("from", "homeFragment");
        startActivity(intent);
    }

    /**
     * 点击定位
     */
    @OnClick(R.id.locate_ll)
    public void clickLocate() {
   /*     CityPicker.getInstance()
                .setFragmentManager(((FragmentActivity) mActivity).getSupportFragmentManager())
                .enableAnimation(true)
                .setLocatedCity(locatedCity)
                .setHotCities(hotCities)
                .setOnPickListener(new OnPickListener() {
                    @Override
                    public void onPick(int position, City data) {
                        if (data != null) {
                            setNewLocationInfo(data.getName());
                        }
                    }

                    @Override
                    public void onLocate() {
//                        mapController.destroyLocation();
//                        mapController.startLocation();
                    }
                })
                .show();*/
        DialogController.showConfirmDialog(mActivity, "温馨提示", "当前只开放温江区");
    }

    /**
     * 在城市列表选择新的城市之后
     *
     * @param newPosition
     */
    private void setNewLocationInfo(String newPosition) {
        positionTv.setText(newPosition);
    }

    private void initHotCities() {
        hotCities = new ArrayList<>();
        hotCities.add(new HotCity("北京", "北京", "101010100"));
        hotCities.add(new HotCity("上海", "上海", "101020100"));
        hotCities.add(new HotCity("广州", "广东", "101280101"));
        hotCities.add(new HotCity("深圳", "广东", "101280601"));
        hotCities.add(new HotCity("杭州", "浙江", "101210101"));
    }

    private View createLine() {
        View line = new View(mActivity);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2);
        layoutParams.setMargins(0, DensityUtil.dp2px(5), 0, 0);
        line.setBackgroundColor(getResources().getColor(R.color.color_e6e6e6));
        line.setLayoutParams(layoutParams);
        return line;
    }

    public AlphaTabsIndicator getMainTabLayout() {
        return ((MainActivity) getActivity()).getmTabLayout();
    }
}
